<?php

App::uses('RequestFacade', 'Network');

/**
 * 微信相关操作
 * 扩展的Utility类名后面都加上Utility，防止类名与Model等其它类重名
 * @author Arlon
 *
 */
class ToutiaoUtility {
	
	static public $client_key='ae8adce1f60d299c';
    static public $secret_key='3dfbdea223d87c79d934c01014a0d096';
	
    /**
     * 
     * @param unknown $post  array(title 标题,content 内容,abstract 摘要)
     * @param unknown $oauth
     */
	public static function new_article($post,$oauth){
	    
	    $access_token = self::getAccessToken($oauth);
	    if($access_token && !is_array($access_token) ){
	        $url = 'https://mp.toutiao.com/open/new_article_post/?access_token='.$access_token.'&client_key='.self::$client_key;
	        $response =  RequestFacade::post($url,$post);
	        $ret  = json_decode($response->body,true);
	        return $ret;
	    }
	    else{
	        return $access_token;
	    }
	}
	
	public static function getAccessToken($oauth){
	    if( time() < $oauth['expires'] ) {
	        return $oauth['oauth_token'];
	    }
	    else{
	        // TODO. refresh oauth_token
	        return array('errcode'=>'111','msg'=>'access token expired.');
	    }
	}
	
	private static function unicode_decode($name,$charset = 'UTF-8'){//GBK,UTF-8,big5
		$pattern = '/\\\u[\w]{4}/i';
		preg_match_all($pattern, $name, $matches);
		//print_r($matches);exit;
		if (! empty ( $matches )) {
			//$name = '';
			for($j = 0; $j < count ( $matches [0] ); $j ++) {
				$str = $matches [0] [$j];
				if (strpos ( $str, '\u' ) === 0) {
					$code = base_convert ( substr ( $str, 2, 2 ), 16, 10 );
					$code2 = base_convert ( substr ( $str, 4 ), 16, 10 );
					$c = chr ( $code ) . chr ( $code2 );
					if ($charset == 'GBK') {
						$c = iconv ( 'UCS-2BE', 'GBK', $c );
					} elseif ($charset == 'UTF-8') {
						$c = iconv ( 'UCS-2BE', 'UTF-8', $c );
					} elseif ($charset == 'BIG5') {
						$c = iconv ( 'UCS-2BE', 'BIG5', $c );
					} else {
						$c = iconv ( 'UCS-2BE', $charset, $c );
					}
					//$name .= $c;
					$name = str_replace($str,$c,$name);
				}
				//else {
				//	$name .= $str;
				//}
			}
		}
		return $name;
	}

}
